using Domain;
using MediatR;
using SqlSugar;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WriteAPI.Command.采购;

namespace WriteAPI.CommandHandle.采购
{
    public class UpdateCgddCommandHandler : IRequestHandler<UpdateCgddCommand, bool>
    {
        private readonly ISqlSugarClient _db;

        public UpdateCgddCommandHandler(ISqlSugarClient db)
        {
            _db = db;
        }

        public async Task<bool> Handle(UpdateCgddCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 开启事务
                bool result = false;
                
                // 使用事务
                _db.Ado.BeginTran();
                
                try
                {
                    // 查询采购订单是否存在
                    var cgdd = await _db.Queryable<Lwp_Cgdd>().FirstAsync(x => x.Id == request.Id);
                    if (cgdd == null)
                    {
                        throw new Exception($"采购订单不存在，ID: {request.Id}");
                    }

                    // 更新采购订单主体
                    cgdd.OrderTheme = request.OrderTheme;
                    cgdd.PurchaseNumber = request.PurchaseNumber;
                    cgdd.SystemNumber = request.SystemNumber ? "1" : "0";
                    cgdd.RelatedPurchase = request.RelatedPurchase;
                    cgdd.RelatedSalesOrder = request.RelatedSalesOrder;
                    cgdd.UnbindSalesOrder = request.UnbindSalesOrder;
                    cgdd.PurchaseDate = request.PurchaseDate;
                    cgdd.SupplierName = request.SupplierName;
                    cgdd.ContactPerson = request.ContactPerson;
                    cgdd.Purchaser = request.Purchaser;
                    cgdd.ContactPhone = request.ContactPhone;
                    cgdd.ContactMethod = request.ContactMethod;
                    cgdd.SettlementMethod = request.SettlementMethod;
                    cgdd.PurchaseDepartment = request.PurchaseDepartment;
                    cgdd.RelatedProject = request.RelatedProject;
                    cgdd.DeliveryAddress = request.DeliveryAddress;
                    cgdd.Remarks = request.Remarks;
                    cgdd.UpdateTime = DateTime.Now;

                    // 更新采购订单主体
                    await _db.Updateable(cgdd).ExecuteCommandAsync();

                    // 获取当前订单的所有明细项
                    var existingItems = await _db.Queryable<Lwp_CgddItem>().Where(x => x.OrderId == request.Id).ToListAsync();
                    
                    // 处理明细项
                    foreach (var itemDto in request.CgddItems)
                    {
                        if (itemDto.Id.HasValue && itemDto.Id.Value > 0)
                        {
                            // 更新已有明细项
                            var existingItem = existingItems.FirstOrDefault(x => x.Id == itemDto.Id.Value);
                            if (existingItem != null)
                            {
                                existingItem.ItemCode = itemDto.ItemCode;
                                existingItem.ItemName = itemDto.ItemName;
                                existingItem.Spec = itemDto.Spec;
                                existingItem.Unit = itemDto.Unit;
                                existingItem.Brand = itemDto.Brand;
                                existingItem.Quantity = itemDto.Quantity;
                                existingItem.TaxRate = itemDto.TaxRate;
                                existingItem.TaxPrice = itemDto.TaxIncludedPrice;
                                existingItem.TaxAmount = itemDto.TotalWithTax;
                                existingItem.UntaxedPrice = itemDto.PriceWithoutTax;
                                existingItem.UntaxedAmount = itemDto.AmountWithoutTax;
                                existingItem.DeliveryDate = itemDto.DeliveryDate ?? DateTime.Now;
                                existingItem.MainUnitQuantity = itemDto.MainUnitQuantity;
                                existingItem.Progress = itemDto.Progress;
                                existingItem.Remarks = itemDto.Remark;
                                existingItem.UpdateTime = DateTime.Now;

                                await _db.Updateable(existingItem).ExecuteCommandAsync();
                            }
                        }
                        else
                        {
                            // 添加新明细项
                            var newItem = new Lwp_CgddItem
                            {
                                OrderId = request.Id,
                                ItemCode = itemDto.ItemCode,
                                ItemName = itemDto.ItemName,
                                Spec = itemDto.Spec,
                                Unit = itemDto.Unit,
                                Brand = itemDto.Brand,
                                Quantity = itemDto.Quantity,
                                TaxRate = itemDto.TaxRate,
                                TaxPrice = itemDto.TaxIncludedPrice,
                                TaxAmount = itemDto.TotalWithTax,
                                UntaxedPrice = itemDto.PriceWithoutTax,
                                UntaxedAmount = itemDto.AmountWithoutTax,
                                DeliveryDate = itemDto.DeliveryDate ?? DateTime.Now,
                                MainUnitQuantity = itemDto.MainUnitQuantity,
                                Progress = itemDto.Progress,
                                Remarks = itemDto.Remark,
                                CreateTime = DateTime.Now,
                                UpdateTime = DateTime.Now
                            };

                            await _db.Insertable(newItem).ExecuteCommandAsync();
                        }
                    }

                    // 删除不再存在的明细项
                    var currentItemIds = request.CgddItems
                        .Where(x => x.Id.HasValue && x.Id.Value > 0)
                        .Select(x => x.Id.Value)
                        .ToList();
                    
                    var itemsToDelete = existingItems
                        .Where(x => !currentItemIds.Contains(x.Id))
                        .ToList();

                    if (itemsToDelete.Any())
                    {
                        await _db.Deleteable<Lwp_CgddItem>()
                            .Where(x => itemsToDelete.Select(i => i.Id).Contains(x.Id))
                            .ExecuteCommandAsync();
                    }

                    // 提交事务
                    _db.Ado.CommitTran();
                    result = true;
                }
                catch (Exception ex)
                {
                    // 回滚事务
                    _db.Ado.RollbackTran();
                    throw;
                }

                return result;
            }
            catch (Exception ex)
            {
                throw new Exception($"更新采购订单失败: {ex.Message}");
            }
        }
    }
} 